<template>
  <div style="height:100%;">
    <div class="phm-tanc-top toptitle"><span class="top-title">1C</span>
      <div class="toptitle-input">
        <p class="form-top-p">
          <el-select v-model="valuek.time" clearable placeholder="选择时间">
            <el-option
              v-for="item in datatime"
              :key="item.detectDate"
              :label="item.detectDate"
              :value="item.detectDate" />
          </el-select>
        </p>
        <p class="form-top-p">
          <el-select v-model="valuek.paramId" style="width: 130px;" multiple collapse-tags clearable placeholder="选择查看参数">
            <el-option
              v-for="item in paramSelects"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
        </p>
        <p class="form-top-p" style="flex:1;text-align:right;">
          <el-switch
            v-model="valuek.switch"
            inactive-color="#ff4949"
            active-text="折线"
            inactive-text="表格" />
        </p>
      </div>
    </div>
    <div v-loading="loading" class="analysisContainer" style="height:calc(100% - 42px);">
      <div class="analysisChartGroup v-flex" style="overflow: hidden;">
        <div v-show="valuek.switch" id="echart-analysis1C" class="analysis1C" style="height:calc(100%);" />
        <el-table
          v-show="!valuek.switch"
          :data="alldata"
          height="100%"
          border
          stripe>
          <el-table-column label="序号" align="center" type="index" width="50" />
          <el-table-column label="公里标" align="center" prop="roadMark" width="100" />
          <el-table-column prop="siteName" align="center" show-overflow-tooltip label="区站" />
          <el-table-column prop="pillarNum" align="center" show-overflow-tooltip label="支柱" />
          <el-table-column v-for="item in paramSelects" :key="item.id" width="100" :prop="item.id" align="center" :label="item.name" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import { find1CLateralAnalysis } from '@/api/cms/data-statistics'
export default {
  name: 'Transverse1C',
  props: {
    datatime: {
      type: Array,
      default: () => []
    },
    params: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      alldata: [],
      valuek: {
        time: '',
        paramId: ['guideHeight1', 'staggers1'],
        switch: true,
        startRoadMark: '',
        endRoadMark: ''
      },
      loading: false,
      queryParams: {},
      paramSelects: [{
        name: '导高-相机',
        id: 'guideHeight1'
      }, {
        name: '拉出值-相机',
        id: 'staggers1'
      }, {
        name: '水平硬点',
        id: 'hardPoint'
      }, {
        name: '弓网接触力',
        id: 'stress'
      }, {
        name: '燃弧',
        id: 'arcing'
      }, {
        name: '接触网电压',
        id: 'pressure'
      }, {
        name: '导高-雷达',
        id: 'guideHeight2'
      }, {
        name: '拉出值-雷达',
        id: 'staggers2'
      }, {
        name: '支柱号',
        id: 'pillarNum'
      }],
      analysisChart: null,
      pillarAxis: [], // 支柱号坐标轴
      chartDatas: {
        detectDate: [], // 横坐标-时间-支柱
        roadMark: [], // 横坐标-公里标-锚段
        guideHeight1: [], // 导高-相机
        staggers1: [], // 拉出值-相机
        hardPoint: [], // 水平硬点
        stress: [], // 弓网接触力
        arcing: [], // 燃弧
        pressure: [], // 接触网电压
        guideHeight2: [], // 导高-雷达
        staggers2: [], // 拉出值-雷达
        pillarNum: [] // 支柱号
      }
    }
  },
  watch: {
    'valuek.time': function(val) {
      this.alldata = []
      if (val && val !== '') {
        // 1C锚段才有时间轴
        this.queryParams = Object.assign({}, this.params, {
          lineCode: this.params.selectLin.split('-')[1],
          lineSiteCode: this.params.lineSiteCode.split('-')[0],
          deptName: this.params.deptCode.split('-')[1],
          detectDate: val
        })
        this.getC1DataByParams(this.queryParams)
      } else {
        this.initAnalysisChart([])
      }
    },
    'valuek.switch': function(val) {
      if (val) {
        this.$nextTick(_ => {
          this.analysisChart.resize()
        })
      }
    },
    'valuek.paramId': function(val) {
      this.setParams()
    },
    datatime() {
      this.valuek.time = ''
    }
  },
  mounted() {
    // this.getC1DataByParams(this.queryParams)
    // 监听屏幕变化，改变echarts尺寸
    const _this = this
    window.addEventListener('resize', function() {
      _this.$nextTick(_ => {
        if (_this.analysisChart) {
          _this.analysisChart.resize()
        }
      })
    })
  },
  beforeDestroy() {
    if (!this.analysisChart) {
      return
    }
    this.analysisChart.dispose()
    this.analysisChart = null
  },
  methods: {
    setParams() {
      this.initAnalysisChart(this.sortBySelected(this.chartDatas))
    },
    getC1DataByParams(param) {
      this.loading = true
      find1CLateralAnalysis(param).then(response => {
        this.loading = false
        // console.log('c1图形数据', response)
        this.clearChartDatas()
        if (response.data && response.data[param.detectDate].length) {
          let lastNum = '' // 上一个支柱号
          response.data[param.detectDate].forEach(item => {
            item.roadMark = this.formatRoad(item.roadMark)
            if (lastNum !== item.pillarNum) {
              this.pillarAxis.push(item.pillarNum)
              lastNum = item.pillarNum
            } else {
              this.pillarAxis.push('')
            }

            for (const key in this.chartDatas) {
              if (key === 'roadMark') {
                this.chartDatas[key].push(this.formatRoad(item[key]))
              } else {
                this.chartDatas[key].push(item[key] || 0)
              }
            }
          })
          this.alldata = response.data[param.detectDate]
        }
        this.initAnalysisChart(this.sortBySelected(this.chartDatas))
      })
    },
    clearChartDatas() {
      this.pillarAxis = []
      for (const key in this.chartDatas) {
        this.chartDatas[key] = []
      }
    },
    sortBySelected(datas) {
      // 数据按参数筛选
      const paramSelected = this.valuek.paramId
      const data = {}
      paramSelected.forEach(item => {
        if (datas[item]) {
          const name = this.paramSelects.filter(e => {
            return e.id === item
          })[0].name
          data[name] = datas[item]
        }
      })
      data['detectDate'] = datas['detectDate']
      data['roadMark'] = datas['roadMark']
      return data
    },
    initAnalysisChart(datas) {
      if (!this.analysisChart) {
        this.analysisChart = echarts.init(document.getElementById('echart-analysis1C'))
      }
      let index = 0
      const length = Object.keys(datas).length - 2
      const height = (90 / length).toFixed(2)
      const titles = []
      const grid = []
      const xAxis = []
      const yAxis = []
      const series = []
      const singleAxis = []
      for (const key in datas) {
        if (key !== 'detectDate' && key !== 'roadMark') {
          titles.push({
            textAlign: 'left',
            text: key,
            top: (height * index) + '%',
            left: 20,
            textStyle: {
              fontSize: 12,
              color: 'black',
              fontWeight: 'normal'
            }
          })
          grid.push({
            height: height + '%',
            top: (2 + height * index) + '%',
            show: true,
            borderColor: 'rgba(64, 158, 255, 0.1)',
            right: 40,
            left: 100,
            bottom: 80
          })
          xAxis.push({
            show: index === (length - 1) ? 1 : 0,
            type: 'category',
            axisLine: {
              lineStyle: {
                color: 'black'
              }
            },
            boundaryGap: false,
            gridIndex: index,
            // data: ['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01']
            data: datas.roadMark
          })
          yAxis.push({
            type: 'value',
            boundaryGap: true,
            scale: true,
            splitLine: {
              show: false
            },
            axisLabel: {
              showMinLabel: false,
              showMaxLabel: false
            },
            axisLine: {
              lineStyle: {
                color: 'black'
              }
            },
            gridIndex: index
          })
          series.push({
            name: key,
            type: 'line',
            smooth: true,
            data: datas[key],
            yAxisIndex: index,
            xAxisIndex: index
          })
          index++
        }
      }
      singleAxis.push({
        left: 120,
        right: 50,
        type: 'category',
        boundaryGap: false,
        // data: this.pillarAxis,
        top: '42%',
        height: 20,
        splitLine: {
          show: false
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          interval: 1,
          color: 'black',
          fontSize: 14
        }
      })
      series.push({
        name: '支柱号',
        coordinateSystem: 'singleAxis',
        type: 'scatter',
        data: []
      })
      const option = {
        title: titles,
        grid: grid,
        tooltip: {
          trigger: 'axis',
          transitionDuration: 0,
          confine: true,
          bordeRadius: 4,
          borderWidth: 1,
          borderColor: '#333',
          backgroundColor: 'rgba(255,255,255,0.9)',
          textStyle: {
            fontSize: 12,
            color: 'black'
          }
        },
        axisPointer: {
          type: 'shadow',
          link: {
            xAxisIndex: 'all'
          }
        },
        xAxis: xAxis,
        yAxis: yAxis,
        singleAxis: singleAxis,
        series: series
      }
      this.analysisChart.setOption(option, true)
    },
    formatRoad(val) {
      if (!val) return ''
      let value = val.toString()
      if (value.startsWith('-')) {
        value = '-K' + value.slice(1).replace(/\./, '+')
      } else {
        value = 'K' + value.replace(/\./, '+')
      }
      if (value.includes('+')) {
        const int = value.slice(0, value.indexOf('+'))
        const decimal = value.slice(value.indexOf('+') + 1)
        value = int +
          '+' +
          (decimal.length <= 3 ? decimal + '0'.repeat(3 - decimal.length) : decimal.slice(0, 3)) +
          '.' +
          (decimal.length <= 3 ? '00' : decimal.slice(3, 6) + '0'.repeat(5 - decimal.length > 0 ? 5 - decimal.length : 0))
      } else {
        value = value + '+000.00'
      }
      return value
    }
  }
}
</script>

<style lang="scss" scoped>
.top-title{
  display: inline-block;
  width: 38px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  background:white;
  border-radius: 4px;
  font-size: 18px;
  color: #409eff;
}
  .analysisContainer {
    overflow: auto;
    color: black;

    .form-button {
      float: none;
    }

    .analysisChartGroup {
      position: relative;
      z-index: 1;
      height: 100%;
    }

    .phwidth {
      display: inline-block;
      width: 150px;
    }

    .chartTitle {
      position: absolute;
      top: 40px;
      z-index: 5;
      width: 100%;
      font-size: 14px;
      font-weight: normal;
      line-height: 24px;
      text-align: center;

      span {
        cursor: pointer;
      }
    }
  }
.toptitle{
  height: 42px;
  display: flex;
  align-items: center;
  margin: 0;
  padding: 10px;
  background: linear-gradient(#F3F5FF, #DFE6FF);
  color: black;
  img{
    height: 14px;
    margin-right: 8px;
  }
}
.form-top-p{
  margin: 0;
  ::v-deep .el-input__icon{
    line-height: 28px;
  }
}
.form-cans {
      display: inline-block;
      height: 28px;
      padding: 0 5px;
      font-size: 14px;
      line-height: 28px;
      color: #fff;
      vertical-align: bottom;
      background-color: #409eff;
      border-color: #409eff;
      border-radius: 4px;
    }
.form-cans:hover{
  cursor: pointer;
}
.toptitle-input{
  margin-left: 20px;
  width: 100%;
  display: flex;
  align-items: center;
}
.toptitle-title{
  color: black;
}
.analysis1C{
  margin-bottom: 10px;
  height: 100%;
  width: 100%;
}
</style>
